package br.com.requisicao.compra.pdf;

import java.util.ResourceBundle;

import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public abstract class FacesUtils {

	private FacesUtils() {
		//
	}

	// Faces
	public static void addMessage(final String message) {
		FacesContext fc = FacesUtils.getFacesContext();
		fc.addMessage(null, new FacesMessage(message));
	}

	public static void addError(final Exception exception) {
		FacesContext fc = FacesUtils.getFacesContext();
		fc.addMessage(null, new FacesMessage(exception.getMessage()));
	}

	public static FacesContext getFacesContext() {
		return FacesContext.getCurrentInstance();
	}

	public static ResourceBundle getResourceBundle(final String name) {
		FacesContext fc = FacesUtils.getFacesContext();
		Application application = fc.getApplication();
		ResourceBundle resource = application.getResourceBundle(fc, name);
		return resource;
	}

	public static <T> T getBean(final String name, final Class<T> clazz) {
		FacesContext fc = FacesUtils.getFacesContext();
		Application app = fc.getApplication();
		ELContext el = fc.getELContext();
		ExpressionFactory factory = app.getExpressionFactory();
		ValueExpression expression = (ValueExpression) factory
				.createValueExpression(el, "#{" + name + "}", clazz);
		T value = (T) expression.getValue(el);
		return value;
	}

	// Http
	public static HttpServletRequest getRequest() {
		FacesContext fc = FacesUtils.getFacesContext();
		return (HttpServletRequest) fc.getExternalContext().getRequest();
	}

	public static HttpServletResponse getResponse() {
		FacesContext fc = FacesUtils.getFacesContext();
		return (HttpServletResponse) fc.getExternalContext().getResponse();
	}

	public static HttpSession getSession() {
		FacesContext fc = FacesUtils.getFacesContext();
		return (HttpSession) fc.getExternalContext().getSession(true);
	}

	public static ServletContext getServletContext() {
		FacesContext fc = FacesUtils.getFacesContext();
		return (ServletContext) fc.getExternalContext().getContext();
	}

}